/**
 * Copyright (c) 时间, Tal.Ben 袁东昊 (ydonghao2@gmail.com).
 *
 * 版权
 */
package com.talben.soudian;

import java.util.Date;
import java.util.List;
import java.util.Properties;
import java.util.UUID;

import org.apache.http.client.CookieStore;
import org.apache.http.client.protocol.ClientContext;
import org.apache.http.cookie.Cookie;
import org.apache.http.protocol.HttpContext;
import org.kymjs.kjframe.KJBitmap;
import org.kymjs.kjframe.bitmap.BitmapConfig;
import org.kymjs.kjframe.utils.KJLoger;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager.NameNotFoundException;

import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.PersistentCookieStore;
import com.talben.soudian.api.ApiHttpClient;
import com.talben.soudian.base.BaseApplication;
import com.talben.soudian.bean.Constants;
import com.talben.soudian.bean.User;
import com.talben.soudian.cache.DataCleanManager;
import com.talben.soudian.ui.LoginActivity;
import com.talben.soudian.ui.UIHelper;
import com.talben.soudian.util.MethodsCompat;
import com.talben.soudian.util.StringUtils;
import com.talben.soudian.util.TLog;
import com.talben.soudian.AppConfig;

/**
 * @Title: AppContext.java
 * @Package com.talben.soudian
 * @Description: 全局应用程序类：用于保存和调用全局应用配置及访问网络数据
 * @author Tal.Ben
 * @date 2015年5月19日 下午11:30:59
 * @version v1.0
 */
public class AppContext extends BaseApplication {

	public static final int PAGE_SIZE = 200;// 默认分页大小
	
	private static AppContext instance;

    private String loginUid;

    private boolean login;
    
    @Override
    public void onCreate() {
        super.onCreate();
        instance = this;
        init();
        initLogin();
//        UIHelper.sendBroadcastForNotice(this);
    }
    
    private void init() {
        // 初始化网络请求
        AsyncHttpClient client = new AsyncHttpClient();
        PersistentCookieStore myCookieStore = new PersistentCookieStore(this);
        client.setCookieStore(myCookieStore);
        ApiHttpClient.setHttpClient(client , this);

        if (ApiHttpClient.getCookie(this) != null) {
			login = true;
		}
        
        // Log控制器
        KJLoger.openDebutLog(true);
        TLog.DEBUG = BuildConfig.DEBUG;

        // Bitmap缓存地址
        BitmapConfig.CACHEPATH = "soudian/imagecache";
    }
    
    private void initLogin() {
        User user = getLoginUser();
        if (null != user && user.getId() > 0) {
            login = true;
            loginUid = user.getuPhone();
        } else {
            this.cleanLoginInfo();
        }
    }
    /**
     * 获得当前app运行的AppContext
     * 
     * @return
     */
    public static AppContext getInstance() {
        return instance;
    }

    public boolean containsProperty(String key) {
        Properties props = getProperties();
        return props.containsKey(key);
    }

    public void setProperties(Properties ps) {
        AppConfig.getAppConfig(this).set(ps);
    }

    public Properties getProperties() {
        return AppConfig.getAppConfig(this).get();
    }

    public void setProperty(String key, String value) {
        AppConfig.getAppConfig(this).set(key, value);
    }

    /**
     * 获取cookie时传AppConfig.CONF_COOKIE
     * 
     * @param key
     * @return
     */
    public String getProperty(String key) {
        String res = AppConfig.getAppConfig(this).get(key);
        return res;
    }

    public void removeProperty(String... key) {
        AppConfig.getAppConfig(this).remove(key);
    }
    
    /**
     * 获取App唯一标识
     * 
     * @return
     */
    public String getAppId() {
        String uniqueID = getProperty(AppConfig.CONF_APP_UNIQUEID);
        if (StringUtils.isEmpty(uniqueID)) {
            uniqueID = UUID.randomUUID().toString();
            setProperty(AppConfig.CONF_APP_UNIQUEID, uniqueID);
        }
        return uniqueID;
    }
    
    /**
     * 获取App安装包信息
     * 
     * @return
     */
    public PackageInfo getPackageInfo() {
        PackageInfo info = null;
        try {
            info = getPackageManager().getPackageInfo(getPackageName(), 0);
        } catch (NameNotFoundException e) {
            e.printStackTrace(System.err);
        }
        if (info == null)
            info = new PackageInfo();
        return info;
    }
    
    /**
     * 保存登录信息
     * 
     * @param username
     * @param pwd
     */
    @SuppressWarnings("serial")
    public void saveUserInfo(final User user) {
        this.loginUid = user.getUaccount();
        this.login = true;
        setProperties(new Properties() {
            {
            	setProperty("user.uaccount", user.getUaccount());
                //setProperty("user.id", user.getId() + "");
            	setProperty("user.id", "1");
                setProperty("user.uname", user.getUname());
                setProperty("user.uphone",user.getuPhone());
                setProperty("user.uemail", user.getuEmail());
                setProperty("user.upassword",user.getuPassword());
                setProperty("user.uscore", user.getuScore());
                setProperty("user.ucoin", user.getuCoin());
                setProperty("user.ugiftlog", user.getuGiftLog());
            }
        });
    }
    
    /**
     * 获得登录用户的信息
     * 
     * @return
     */
    public User getLoginUser() {
        User user = new User();
        user.setId(StringUtils.toInt(getProperty("user.id"), 0));
        user.setUname(getProperty("user.uname"));
        user.setuPhone(getProperty("user.uphone"));
        user.setuEmail(getProperty("user.uemail"));
        user.setuPassword(getProperty("user.upassword"));
        user.setuScore(getProperty("user.uscore"));
        user.setuCoin(getProperty("user.ucoin"));
        user.setuGiftLog(getProperty("user.ugiftlog"));
        return user;
    }
	
    /**
     * 更新用户信息
     * 
     * @param user
     */
    @SuppressWarnings("serial")
    public void updateUserInfo(final User user) {
        setProperties(new Properties() {
            {
            	setProperty("user.id", "1");
                setProperty("user.uname", user.getUname());
                setProperty("user.uphone",user.getuPhone());
                setProperty("user.uemail", user.getuEmail());
                setProperty("user.uscore", user.getuScore());
                setProperty("user.ucoin", user.getuCoin());
                setProperty("user.ugiftlog", user.getuGiftLog());
            }
        });
    }
    
    /**
     * 清除登录信息
     */
    public void cleanLoginInfo() {
        this.loginUid = "0";
        this.login = false;
        removeProperty("user.uname", "user.uphone", "user.uemail", 
                "user.uscore", "user.ucoin", "user.ugiftlog");
    }
    
    public String getLoginUid() {
    	User user = getLoginUser();
        return user.getUaccount();
    }

    public boolean isLogin() {
    	//暂时根据cookie来查询是否登陆
//    	CookieStore cookieStore = this.getCookieStore(this);
//    	List<Cookie> cookies= cookieStore.getCookies();
//        return this.checkExperid(cookies);
    	return (this.getProperty("user.uphone") != null);
    }
    
    /**
     * 用户注销
     */
    public void Logout() {
        cleanLoginInfo();
        //
        ApiHttpClient.cleanCookie();
        this.cleanCookie();
        this.login = false;
        this.loginUid = "0";

        //推荐后的广播。
        //Intent intent = new Intent(Constants.INTENT_ACTION_LOGOUT);
        //sendBroadcast(intent);
    }
    
    /**
     * 清除保存的缓存
     */
    public void cleanCookie() {
        removeProperty(AppConfig.CONF_COOKIE);
    }
    
    /**
     * 清除app缓存
     */
    public void clearAppCache() {
        DataCleanManager.cleanDatabases(this);
        // 清除数据缓存
        DataCleanManager.cleanInternalCache(this);
        // 2.2版本才有将应用缓存转移到sd卡的功能
        if (isMethodsCompat(android.os.Build.VERSION_CODES.FROYO)) {
            DataCleanManager.cleanCustomCache(MethodsCompat
                    .getExternalCacheDir(this));
        }
        // 清除编辑器保存的临时内容
        Properties props = getProperties();
        for (Object key : props.keySet()) {
            String _key = key.toString();
            if (_key.startsWith("temp"))
                removeProperty(_key);
        }
        new KJBitmap().cleanCache();
    }

    /**
     * 判断当前版本是否兼容目标版本的方法
     * 
     * @param VersionCode
     * @return
     */
    public static boolean isMethodsCompat(int VersionCode) {
        int currentVersion = android.os.Build.VERSION.SDK_INT;
        return currentVersion >= VersionCode;
    }

    public static boolean isFristStart() {
        return getPreferences().getBoolean(AppConfig.KEY_FRITST_START, true);
    }

    public static void setFristStart(boolean frist) {
        set(AppConfig.KEY_FRITST_START, frist);
    }
    
    public void cleanCookieStore(Context context){
        // Clear cookies from persistent store  
    	this.getCookieStore(context).clear();
    }
    
    public static void setCookie(Context context){
    	AsyncHttpClient client = ApiHttpClient.getHttpClient();
//		HttpContext httpContext = client.getHttpContext();
		//获取AsyncHttpClient中的CookieStore
//		CookieStore cookies = (CookieStore) httpContext.getAttribute(ClientContext.COOKIE_STORE);
//    if(cookies!=null){
//        for(Cookie c:cookies.getCookies()){
//            System.out.println("main before ~~"+c.getName()+"---"+c.getValue());
//        }
//    }else{
//        System.out.println("main  before~~"+"---"+"cookies is null");
//    }
		
		PersistentCookieStore myCookieStore = new PersistentCookieStore(context);
		client.setCookieStore(myCookieStore);
        
//        if(cookies!=null){
//            for(Cookie c:cookies.getCookies()){
//                System.out.println("main after ~~"+c.getName()+"---"+c.getValue());
//            }
//        }else{
//            System.out.println("main  after~~"+"---"+"cookies is null");
//        }
    }
    
    public static CookieStore getCookieStore(Context context){
    	AsyncHttpClient client = ApiHttpClient.getHttpClient();
    	return (CookieStore) client.getHttpContext().getAttribute(ClientContext.COOKIE_STORE);
    }
    
    
    // 检查过期时间
   	private boolean checkExperid(List<Cookie> cookies) {
   		for (Cookie cookie : cookies) {
   			if ("sessionid".equals(cookie.getName())) {
   				Date now = new Date();
   				if (now.compareTo(cookie.getExpiryDate()) > 0) {
   					return false;
   				}
   			}
   		}
   		return true;
   	}
}

